package accounts

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
)

// 数据访问层(负责持久化数据)

type AccountLogDao struct {
	runner *dbx.TxRunner
}

// 通过流水编号查询流水记录
func (dao *AccountLogDao) GetOne(logNo string) *AccountLog{
	accountLog := &AccountLog{
		LogNo: logNo,
	}
	ok, err := dao.runner.GetOne(accountLog)
	if err != nil{
		logrus.Error(err)
		return nil
	}
	if !ok {
		logrus.Warn(fmt.Sprintf("logNo:[%s]的记录不存在", logNo))
		return nil
	}
	return accountLog
}

// 通过交易编号查询流水记录
func (dao *AccountLogDao) GetByTradeNo(tradeNo string) *AccountLog{

	accountLog := &AccountLog{}
	sql := "select * from account_log where trade_no = ?"
	ok, err := dao.runner.Get(accountLog, sql, tradeNo)
	if err != nil{
		logrus.Error(err)
		return nil
	}
	if !ok {
		logrus.Warn(fmt.Sprintf("tradeNo:[%s]的记录不存在", tradeNo))
		return nil
	}
	return accountLog
}

// 流水记录的写入
func (dao *AccountLogDao) Insert(log *AccountLog) (id int64, err error) {
	rs, err := dao.runner.Insert(log)
	if err != nil {
		return 0, err
	}
	return rs.LastInsertId()
}